package com.share.user.service.impl;

import java.util.List;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.constant.UserConstants;
import com.share.common.core.context.SecurityContextHolder;
import com.share.common.core.exception.ServiceException;
import com.share.user.api.domain.UpdateUserLogin;
import com.share.user.domain.UserLoginLog;
import com.share.user.mapper.UserLoginLogMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;
import com.share.user.mapper.UserInfoMapper;
import com.share.user.api.domain.UserInfo;
import com.share.user.service.IUserInfoService;

/**
 * 用户Service业务层处理
 *
 * @author atguigu
 * @date 2025-03-24
 */
@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    UserLoginLogMapper userLoginLogMapper;

    // 微信小程序操作服务类(在WxMaConfig做了基本属性的配置)
    @Resource
    WxMaService wxMaService;

    /**
     * 查询用户列表
     *
     * @param userInfo 用户
     * @return 用户
     */
    @Override
    public List<UserInfo> selectUserInfoList(UserInfo userInfo) {
        return userInfoMapper.selectUserInfoList(userInfo);
    }

    /**
     * 微信小程序登录
     *
     * @param code 微信小程序登录时返回的code
     * @return
     */
    @Override
    public UserInfo wxLogin(String code) {
        String openId = null;
        try {
            //获取openId
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openId = sessionInfo.getOpenid();
            log.info("【小程序授权】 openId={}", openId);
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new ServiceException("微信登录失败");
        }
        // 根据openId查询用户信息表
        UserInfo userInfo = this.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openId));
        if (null == userInfo) {
            //userInfo等于null，说明是第一次登录，需要注册,向用户表中添加一条数据
            userInfo = new UserInfo();
            userInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            userInfo.setWxOpenId(openId);
            this.save(userInfo);

        }
        return userInfo;
    }

    /**
     * 更新用户登录信息
     * @param updateUserLogin
     * @return
     */
    @Override
    public Boolean updateUserLogin(UpdateUserLogin updateUserLogin) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(updateUserLogin.getUserId());
        userInfo.setLastLoginIp(updateUserLogin.getLastLoginIp());
        userInfo.setLastLoginTime(updateUserLogin.getLastLoginTime());
        userInfoMapper.updateById(userInfo);

        //登录日志
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setUserId(userInfo.getId());
        userLoginLog.setMsg("小程序登录");
        userLoginLog.setIpaddr(userInfo.getLastLoginIp());
        userLoginLogMapper.insert(userLoginLog);
        return true;
    }

    /**
     * 免押金操作，实际应该通过调用微信支付分相关接口来实现，这里我们只是模拟
     * @return
     */
    @Override
    public Boolean isFreeDeposit() {
        //微信支付分
        //https://pay.weixin.qq.com/wiki/doc/apiv3/payscore.php?chapter=18_1&index=2
        // 默认免押金，模拟实现
        UserInfo userInfo = this.getById(SecurityContextHolder.getUserId());
        // 押金状态（0：未验证 1：免押金 2：已交押金）
        userInfo.setDepositStatus(UserConstants.FREE_DEPOSIT);
        this.updateById(userInfo);
        return true;
    }

}
